package com.superbytecode.stencil.utils;

import lombok.experimental.UtilityClass;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: code-stencil
 * @Package: com.superbytecode.stencil.utils
 * @ClassName: FieldUtil
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/10/11 20:58
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.cn Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@UtilityClass
public class FieldUtil {
    public static final char UNDER_LINE = '_';

    /**
     * 下划线字段转驼峰
     * <pre>
     * name                --> name
     * _name               --> _name
     * name__              --> name__
     * __name              --> __name
     * __name_             --> __name_
     * user_name           --> userName
     * user_address_detail --> userAddressDetail
     * user__name          --> userName
     * _user_name          --> _userName
     * _user__name         --> _userName
     * user_name_          --> userName_
     * _user_name_         --> _userName_
     * </pre>
     *
     * @param field 字段
     * @return 返回转换后的字段
     */
    public String underscoreToCamelCase(String field) {
        if (StringUtil.isEmpty(field)) return "";
        // 首字母前存在特殊字符/分割字符个数
        int leadingOffset = StringUtil.findSettingOffset(field, UNDER_LINE, false);
        // 尾部母后存在特殊字符/分割字符个数
        int trailingOffset = StringUtil.findSettingOffset(field, UNDER_LINE, true);
        // 去除首尾'_'
        field = StringUtil.trim(field, UNDER_LINE);
        String[] arr = field.split("_+");
        return join(arr, UNDER_LINE, leadingOffset, trailingOffset);
    }

    public static void main(String[] args) {
        String field = underscoreToCamelCase("gen_template_group");
        System.out.println(field);
    }

    /**
     * 驼峰字段拼接
     *
     * @param arr     字符串以"_"拆分个数
     * @param setting 特殊字符
     * @param leading 首字母特殊字符个数
     * @param tailing 尾字母特殊字符个数
     * @return 驼峰字符串
     */
    @SuppressWarnings("all")
    private static String join(String[] values, char setting, int leading, int tailing) {
        if (values.length > 1) {
            for (int i = 1; i < values.length; i++) {
                values[i] = StringUtil.capitalizeFirstLetter(values[i]);
            }
        }
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < leading; i++) {
            ret.append(setting);
        }
        ret.append(String.join("", values));
        for (int i = 0; i < tailing; i++) {
            ret.append(setting);
        }
        return StringUtil.trim(ret.toString(), setting);
    }
}